"""Calculate the similarity between two texts with different languages"""
import jieba

from utils import lemma, match, load_dict


class Similarity(object):
    """Base class for similarity calculation"""

    def score(self, txt1, txt2, **kwargs):
        """The similarity score of two texts"""
        pass


class SimilarityCount(Similarity):
    def __init__(self, dict_fn="ecdict.gb.txt"):
        self.ezdict = load_dict(dict_fn)

    def _len_penality(self, e_len, z_len):
        if e_len > z_len:
            return e_len / float(z_len)
        else:
            return z_len / float(e_len)

    def score(self, txt1, txt2, **kwargs):
        lemma_list = lemma(txt1)
        s = 0.0
        for t in lemma_list:
            if match(t, txt2, self.ezdict):
                s += 1

        e_len = len(lemma_list)
        z_len = len(list(jieba.cut(txt2)))

        return (s / e_len) / self._len_penality(e_len, z_len)


if __name__ == "__main__":
    e1 = "I like this book."
    z1 = "我喜欢这本书。"
    z2 = "我非常非常喜欢这书。"
    z3 = "这本书不错。"

    sim = SimilarityCount()
    print(sim.score(e1, z1), sim.score(e1, z2), sim.score(e1, z3))
